package eu.dicode.analysis.demonstrator;

import eu.dicode.analysis.demonstrator.model.HomeCommand;
import eu.dicode.analysis.demonstrator.util.CommandPopulator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.*;
import java.util.Hashtable;
import java.util.Properties;

/**
 * Reads a dumped sequencefile containing the results of our histogram analysis and returns the results per
 * query as json formatted string.
 */
@Controller
public class HistogramDataController {

  private final Hashtable<String, Integer> queries = new Hashtable<String, Integer>();
  private final File histogramRawData;

  public HistogramDataController() throws IOException {
    InputStream stream = null;
    try {
      // we ship this file, if it is not there we want to fail with some sort of runtime error
      stream = this.getClass().getResourceAsStream("/dicode.analysis.demonstrator.properties");
      Properties props = new Properties();
      props.load(stream);
      String queryString = props.getProperty("eu.dicodeproject.analysis.histogram.queries");
      int i = 0;
      for (String query : queryString.split(":")) {
        this.queries.put(query, i);
        i++;
      }

      this.histogramRawData = new File(props.getProperty(("eu.dicodeproject.analysis.histogram.location")));
    } finally {
      if (stream != null) stream.close();
    }
  }

  // TODO throw all of that out and possibly move it directly to HBase or some other DB - file parsing sucks.
  @RequestMapping(value="/data/{queryString}.hist", method = RequestMethod.GET)
  public void data(@PathVariable String queryString, final Model model, final Writer responseWriter) throws IOException, FileNotFoundException {
    Integer queryId = this.queries.get(queryString);
    BufferedReader reader = new BufferedReader(new FileReader(this.histogramRawData));
    String line = reader.readLine();
    StringBuffer result = new StringBuffer("[[");
    System.out.println(queryId);
    while (line != null) {
      if (line.startsWith("Key: [" + queryId)) {
        String[] entries = line.split(" ");
        String x = entries[2].substring(0, entries[2].length() - 2);
        String y = entries[4];
        if (result.length() > 2) {
          result.append(", ");
        }
        result.append("[").append(x).append(",").append(y).append("]");
        System.out.println(result);
      }
      line = reader.readLine();
    }
    if (result.length() == 2) result.append("[10350, 1]");
    result.append("]]");
    responseWriter.write(result.toString());
  }
}
